<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { fetchGetAllRoles } from '@/service/api/system-manage';
import { $t } from '@/locales';
import { enableStatusOptions, userGenderOptions } from '@/constants/business';
import { REG_USER_NAME } from '@/constants/reg';

// 定义组件名称
defineOptions({ name: 'OperateDrawer' });

/**
 * 组件属性定义
 */
interface Props {
  /** 操作类型：添加或编辑 */
  operateType: UI.TableOperateType;
  /** 被编辑的行数据 */
  rowData?: Api.SystemManage.User | null;
}

// 声明组件属性
const props = defineProps<Props>();

/**
 * 事件定义
 */
interface Emits {
  /** 表单提交成功后触发 */
  (e: 'submitted'): void;
}

// 声明组件事件
const emit = defineEmits<Emits>();

/**
 * 抽屉显示状态
 * 使用v-model双向绑定
 */
const visible = defineModel<boolean>('visible', {
  default: false
});

// 表单相关hooks
const { formRef, validate, restoreValidation } = useForm();
const { defaultRequiredRule } = useFormRules();

/**
 * 抽屉标题
 * 根据操作类型动态计算
 */
const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: $t('page.manage.user.addUser'), // 添加用户
    edit: $t('page.manage.user.editUser') // 编辑用户
  };
  return titles[props.operateType];
});

/**
 * 表单数据模型类型定义
 * 选择User对象中需要的字段
 */
type Model = Pick<
  Api.SystemManage.User,
  'userName' | 'userGender' | 'nickName' | 'userPhone' | 'userEmail' | 'userRoles' | 'status'
>;

// 表单数据模型
const model = ref(createDefaultModel());

/**
 * 创建默认表单数据
 * @returns 默认的空表单数据
 */
function createDefaultModel(): Model {
  return {
    userName: '',
    userGender: undefined,
    nickName: '',
    userPhone: '',
    userEmail: '',
    userRoles: [],
    status: undefined
  };
}

/**
 * 表单验证规则字段类型
 */
type RuleKey = Extract<keyof Model, 'userName' | 'status'>;

/**
 * 表单验证规则
 */
const rules: Record<RuleKey, App.Global.FormRule> = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: REG_USER_NAME, message: '用户名格式不正确', trigger: 'blur' }
  ],
  status: defaultRequiredRule
};

/** 可选角色选项 */
const roleOptions = ref<CommonType.Option<string>[]>([]);

/**
 * 获取所有角色选项
 * 从API加载角色数据
 */
async function getRoleOptions() {
  const { error, data } = await fetchGetAllRoles();

  if (!error) {
    const options = data.map(item => ({
      label: item.roleName,
      value: item.roleCode
    }));

    // 将当前用户已有角色添加到选项中
    const userRoleOptions = model.value.userRoles.map(item => ({
      label: item,
      value: item
    }));

    roleOptions.value = [...userRoleOptions, ...options];
  }
}

/**
 * 初始化表单数据
 * 如果是编辑状态，则填充当前数据
 */
function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

/**
 * 关闭抽屉
 */
function closeDrawer() {
  visible.value = false;
}

/**
 * 提交表单
 * 验证通过后提交数据到服务器
 */
async function handleSubmit() {
  await validate();
  
  // 模拟API请求成功
  // 实际项目中应该调用真正的API
  console.log('提交数据:', model.value);
  console.log('操作类型:', props.operateType);
  
  // 显示成功消息
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

/**
 * 监听抽屉显示状态
 * 显示时初始化表单数据
 */
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
  }
});
</script>

<template>
  <!-- 用户操作抽屉 -->
  <ElDrawer v-model="visible" :title="title" :size="360">
    <!-- 表单区域 -->
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <!-- 用户名 -->
      <ElFormItem :label="$t('page.manage.user.userName')" prop="userName">
        <ElInput v-model="model.userName" :placeholder="$t('page.manage.user.form.userName')" />
      </ElFormItem>
      
      <!-- 性别 -->
      <ElFormItem :label="$t('page.manage.user.userGender')" prop="userGender">
        <ElRadioGroup v-model="model.userGender">
          <ElRadio v-for="item in userGenderOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
        </ElRadioGroup>
      </ElFormItem>
      
      <!-- 昵称 -->
      <ElFormItem :label="$t('page.manage.user.nickName')" prop="nickName">
        <ElInput v-model="model.nickName" :placeholder="$t('page.manage.user.form.nickName')" />
      </ElFormItem>
      
      <!-- 手机号 -->
      <ElFormItem :label="$t('page.manage.user.userPhone')" prop="userPhone">
        <ElInput v-model="model.userPhone" :placeholder="$t('page.manage.user.form.userPhone')" />
      </ElFormItem>
      
      <!-- 邮箱 -->
      <ElFormItem :label="$t('page.manage.user.userEmail')" prop="userEmail">
        <ElInput v-model="model.userEmail" :placeholder="$t('page.manage.user.form.userEmail')" />
      </ElFormItem>
      
      <!-- 状态 -->
      <ElFormItem :label="$t('page.manage.user.userStatus')" prop="status">
        <ElRadioGroup v-model="model.status">
          <ElRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
        </ElRadioGroup>
      </ElFormItem>
      
      <!-- 用户角色 -->
      <ElFormItem :label="$t('page.manage.user.userRole')" prop="userRoles">
        <ElSelect v-model="model.userRoles" multiple :placeholder="$t('page.manage.user.form.userRole')">
          <ElOption v-for="{ label, value } in roleOptions" :key="value" :label="label" :value="value" />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    
    <!-- 抽屉底部操作按钮 -->
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeDrawer">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDrawer>
</template>

<style scoped>
/* 可以添加自定义样式 */
</style> 